<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import VueOfficePdf from '@vue-office/pdf';

// 文档内容
const docSrc = ref(null);
// 渲染状态
const renderComplete = ref(false);

// 渲染完成回调
const onRenderComplete = () => {
  renderComplete.value = true;
  console.log('文档渲染完成');
  // 渲染完成后，可以手动触发重绘来确保内容显示
  setTimeout(() => {
    window.dispatchEvent(new Event('resize'));
  }, 100);
};

// 文档渲染错误回调
const onDocError = (error) => {
  console.error('文档渲染错误:', error);
  ElMessage.error(`文档渲染失败: ${error.message || '未知错误'}`);
};

// 加载文档
onMounted(async () => {
  try {
    // 使用fetch加载PDF文件
    const response = await fetch('/docs/user/症状自评量表测评报告.pdf');
    if (!response.ok) {
      throw new Error(`无法加载文档: ${response.statusText}`);
    }
    
    // 将PDF内容转换为arrayBuffer
    docSrc.value = await response.arrayBuffer();
    
  } catch (error) {
    console.error('文档加载失败:', error);
    ElMessage.error(`文档加载失败: ${error.message}`);
  }
});

// 下载PDF报告
const downloadPDF = async () => {
  try {
    // 获取PDF文件
    const response = await fetch('/docs/user/症状自评量表测评报告.pdf');
    if (!response.ok) {
      throw new Error(`无法加载PDF文件: ${response.statusText}`);
    }
    
    // 获取文件名
    const fileName = '症状自评量表测评报告.pdf';
    
    // 创建Blob对象
    const blob = await response.blob();
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('PDF报告下载成功！');
  } catch (error) {
    console.error('PDF下载失败:', error);
    ElMessage.error(`PDF下载失败: ${error.message}`);
  }
};
</script>

<template>
<div class="report-box">
  <div class="download-area">
    <el-button type="primary" @click="downloadPDF" size="small" style="margin-bottom: 15px;">下载PDF报告</el-button>
  </div>
  <el-scrollbar height="470px">
    <div class="report-container">
      <!-- 使用vue-office-pdf组件显示文档 -->
        <VueOfficePdf 
          v-if="docSrc" 
          :src="docSrc" 
          :style="{ width: '100%' }"
          @render-complete="onRenderComplete"
          @error="onDocError"
        />
      
      <!-- 如果文档未加载成功，显示错误提示 -->
      <div v-else class="loading-tip">
        文档加载中...
      </div>
    </div>
  </el-scrollbar>
</div>
</template>

<style scoped>
.report-box {
  margin: 0 auto;
  width: 1200px;
  min-height: 200px;
  background-color: #f9f9f9;
}
.download-area {
  padding: 15px 20px 0;
  text-align: right;
}

.report-container {
  padding: 20px;
}

/* 加载提示样式 */
.loading-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  font-size: 16px;
  color: #666;
}
</style>